<template>
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="名称" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryParam.providerName" allowClear placeholder="请输入名称" />
      </a-form-item>
      <a-form-item class="smart-query-form-item smart-margin-left10">
        <a-button-group>
          <a-button type="primary" @click="onSearch">
            <template #icon>
              <ReloadOutlined />
            </template>
            查询
          </a-button>
        </a-button-group>
      </a-form-item>
    </a-row>
  </a-form>

  <a-card size="small" :bordered="true">
    <a-row>
      <a-col :span="12">
        <a-table
          size="small"
          bordered
          :loading="tableLoading"
          rowKey="id"
          :columns="columns"
          :data-source="tabData"
          :pagination="false"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          style="height: 450px; overflow-y: auto"
        >
          <template #bodyCell="{ record, column }">
            <template v-if="column.dataIndex === 'category'">
              <div class="smart-table-operate">
                {{ record.category == 'static' ? '静态' : '动态' }}
              </div>
            </template>
          </template>
        </a-table>
        <div style="float: right; right: 10px">
          <a-pagination
            v-model:current="queryParam.pageNumber"
            v-model:page-size="queryParam.pageSize"
            :page-size-options="pageSizeOptions"
            :total="queryParam.total"
            show-size-changer
            @showSizeChange="onShowSizeChange"
            @change="onSizeChange"
          >
          </a-pagination>
        </div>
      </a-col>
      <a-col :span="12">
        <div style="height: 500px; overflow-y: auto">
          <!-- <a-directory-tree v-model:expandedKeys="expandedKeys" v-model:selectedKeys="selectedKeys"
                    v-model:checkedKeys="checkedKeys" checkable :tree-data="treeData">
                    <template #title="{ title, key }">
                        <span>{{ title }}</span>
                    </template>
                </a-directory-tree> -->
          <a-directory-tree
            v-model:expandedKeys="expandedKeys"
            v-model:selectedKeys="selectedKeys"
            v-model:checkedKeys="checkedKeys"
            style="width: 100%"
            :tree-data="treeData"
            :dropdown-style="{ maxHeight: '600px', overflow: 'auto' }"
            tree-checkable
            allow-clear
            tree-default-expand-all
            :show-checked-strategy="SHOW_PARENT"
            tree-node-filter-prop="title"
          />
        </div>
      </a-col>
    </a-row>
  </a-card>
</template>

<script setup>
import { onMounted, reactive, ref, watch, createVNode } from 'vue';
import { zhuzhiApi } from '/src/api/security/zhuzhi/api';
import { Modal, message, TreeSelect } from 'ant-design-vue';

import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import _ from 'lodash';
import { SmartLoading } from '/src/components/framework/smart-loading';
import { smartSentry } from '/src/lib/smart-sentry';

const expandedKeys = ref(['1']);
const SHOW_PARENT = TreeSelect.SHOW_PARENT;

// -----------------------  筛选 ---------------------
const queryParam = ref({
  roleName: '',
  pageSize: 10,
  pageNumber: 1,
  total: 0,
});

async function handleOk() {
  form.status = form.status ? 1 : 0;
  if (disabledCode.value) {
    let res = await socialsproviderApi.updateSocialsProviderById(form);

    if (res.code == 0) {
      message.success('修改成功');
    } else {
      message.error('修改失败');
    }
  } else {
    let res = await socialsproviderApi.addSocialsProvider(form);

    if (res.code == 0) {
      message.success('新建成功');
    } else {
      message.error('新建失败');
    }
  }

  visible.value = false;
  init();
}

// ----------------------- 表单 ---------------------

const formRef = ref();

const disabledCode = ref(false);

const formDefault = {
  id: undefined,
  icon: undefined,
  provider: undefined,
  providerName: undefined,
  clientId: undefined,
  clientSecret: undefined,
  agentId: undefined,
  scanCode: 'false',
  display: 'false',
  sortIndex: 1,
  status: 0,
};

let form = reactive({ ...formDefault });

// 表单规则
const rules = {
  // icon: [{ required: true, message: '请输入图标' }],
  // provider: [{ required: true, message: '请输入提供者' }],
  // providerName: [{ required: true, message: '请输入名称' }],
  // clientId: [{ required: true, message: '请输入凭证' }],
  // clientSecret: [{ required: true, message: '请输入密钥' }],
  // agentId: [{ required: true, message: '请输入agentId' }],
  // scanCode: [{ required: true, message: '请选择扫码登陆' }],
  // sortIndex: [{ required: true, message: '请输入排序' }],
  // status: [{ required: true, message: '请选择状态' }],
};

const visible = ref(false);
const title = ref('');
const onShowSizeChange = (current, pageSize) => {
  queryParam.value.pageNumber = current;
  queryParam.value.pageSize = pageSize;
  init();
};
const onSizeChange = (page, pageSize) => {
  queryParam.value.pageNumber = page;
  queryParam.value.pageSize = pageSize;
  init();
};

function add() {
  form.id = undefined;
  form.icon = undefined;
  form.provider = undefined;
  form.providerName = undefined;
  form.clientId = undefined;
  form.clientSecret = undefined;
  form.agentId = undefined;
  form.scanCode = 'false';
  form.display = 'false';
  form.sortIndex = 1;
  form.status = 0;
  title.value = '新建';
  visible.value = true;
  disabledCode.value = false;
}
//

// ----------------------- 部门树的展示 ---------------------
const tableLoading = ref(false);

const tabData = ref([]);

const treeData = ref([]);

const pageSizeOptions = ref(['10', '20', '30', '40', '50']);
const onSelectChange = (selectedRowKeys) => {
  // state.selectedRowKeys = selectedRowKeys;
};

const columns = ref([
  {
    title: '角色名称',
    dataIndex: 'roleName',
    key: 'roleName',
  },
  {
    title: '类型',
    dataIndex: 'category',
    key: 'category',
  },
]);

onMounted(() => {
  init();
  inttTree();
});
//gettreeData
async function inttTree() {
  try {
    let res = await zhuzhiApi.gettreeData();
    if (res.code == 0) {
      treeData.value = buildTree(res.data.nodes);
    }
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
  }
}

function buildTree(data) {
  const tree = [];
  const map = {};
  data.forEach((item) => {
    // map[item.key] = { ...item, children: [] };
    map[item.key] = { title: item.title, key: item.key, parentKey: item.parentKey, children: [] };
  });
  data.forEach((item) => {
    const { parentKey } = item;
    if (parentKey === '0') {
      tree.push(map[item.key]);
    } else {
      if (map[parentKey]) {
        map[parentKey].children.push(map[item.key]);
      }
    }
  });
  return tree;
}

// 查询部门列表并构建 部门树
async function init() {
  try {
    tableLoading.value = true;
    let res = await zhuzhiApi.getaccessList(queryParam.value);
    if (res.code == 0) {
      tabData.value = res.data.rows;
      queryParam.value.total = res.data.records;
    }
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

// 重置
function resetQuery() {
  queryParam.value.roleName = '';
  queryParam.value.pageSize = 10;
  queryParam.value.pageNumber = 1;
  queryParam.value.total = 0;
  onSearch();
}

// 搜索
function onSearch() {
  init();
}

// ----------------------- 表单操作：添加部门/修改部门/删除部门/上下移动 ---------------------

// 编辑
function updateRecord(e) {
  getRecordById(e);
  title.value = '编辑';
  visible.value = true;
}

async function getRecordById(id) {
  let res = await socialsproviderApi.getSocialsProviderById(id);
  disabledCode.value = true;
  if (res.code == 0) {
    form.id = res.data.id;
    form.icon = res.data.icon;
    form.provider = res.data.provider;
    form.providerName = res.data.providerName;
    form.clientId = res.data.clientId;
    form.clientSecret = res.data.clientSecret;
    form.agentId = res.data.agentId;
    form.scanCode = res.data.scanCode;
    form.display = res.data.display;
    form.sortIndex = res.data.sortIndex;
    form.status = res.data.status;
  }
}

// 删除
function deleterRecord(id) {
  Modal.confirm({
    title: '提醒',
    icon: createVNode(ExclamationCircleOutlined),
    content: '确定要删除吗?',
    okText: '删除',
    okType: 'danger',
    async onOk() {
      SmartLoading.show();
      try {
        await socialsproviderApi.deleteSocialsProvider(id);
        init();
      } catch (error) {
        smartSentry.captureError(error);
      } finally {
        SmartLoading.hide();
      }
    },
    cancelText: '取消',
    onCancel() {},
  });
}
</script>

<style scoped lang="less"></style>